﻿using System.Collections.Generic;
using System.Web.Mvc;
using Reece.Open.Mvc.Atom.Interfaces;
using Reece.Open.Mvc.Atom.Models;

namespace Reece.Open.Mvc.Atom
{
    public class AtomResult : ActionResult
    {

        private IAtomValidator _validator;
        private IAtomValidator Validator
        {
            get { return _validator ?? (_validator = Factories.ValidatorFactory.GetAtomValidator()) ; }
            set { _validator = value; }
        }

        private IAtomSerializer _serializer;
        private IAtomSerializer Serializer
        {
            get { return _serializer ?? (_serializer = Factories.SerializerFactory.GetSerializer()); }
            set { _serializer = value; }
        }

        private object _feed;

        public AtomResult(object feed)
        {
            _feed = feed;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            IList<ValidationErrors> validationErrors = Validator.ValidateFeed(_feed);
            if ( validationErrors != null && validationErrors.Count > 0 )
            {
                throw new AtomValidationException("Feed Object Invalid", validationErrors);
            }
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ContentType = "application/atom+xml";
            Serializer.Serialize(context.HttpContext.Response.OutputStream, _feed);
        }
    }
}
